package com.bang.study.aggs;

import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.metrics.avg.InternalAvg;
import org.elasticsearch.search.aggregations.metrics.cardinality.InternalCardinality;
import org.elasticsearch.search.aggregations.metrics.percentiles.Percentile;
import org.elasticsearch.search.aggregations.metrics.percentiles.tdigest.InternalTDigestPercentiles;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;
import java.util.Iterator;

/**
 * @ClassName: MuchAggsSearch
 * @author: BANG
 * @Date: 2020/01/15 16:57
 * @Version: 1.0
 * @Modified By:
 * @Desc: TODO
 *
 * GET /test_website/logs/_search
 * {
 *   "size": 0,
 *   "aggs": {
 *     "latency_percentiles": {
 *       "percentiles": {
 *         "field": "latency",
 *         "percents": [
 *           50,
 *           95,
 *           99
 *         ]
 *       }
 *     },
 *     "latency_avg": {
 *       "avg": {
 *         "field": "latency"
 *       }
 *     }
 *   }
 * }
 */
public class PencentilesSearch {


    public static void main(String[] args) throws Exception {
        Settings settings = Settings.builder()
                .put("cluster.name", "elasticsearch")
                .put("client.transport.sniff", true)
                .build();

        TransportClient client = new PreBuiltTransportClient(settings).addTransportAddress(
                new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300)
        );

        SearchResponse searchResponse = client.prepareSearch("test_website").setTypes("logs")
                .addAggregation(AggregationBuilders.percentiles("latency_percentiles")
                        .field("latency")
                        .percentiles(50,95,99)
                        )
                .addAggregation(AggregationBuilders.avg("latency_avg").field("latency"))
                .setSize(0)
                .get();

        InternalAvg latency_avg = searchResponse.getAggregations().get("latency_avg");
        System.err.println("latency_avg : "+latency_avg.getValueAsString());

        InternalTDigestPercentiles latency_percentiles = searchResponse.getAggregations().get("latency_percentiles");
        Iterator<Percentile> iterator = latency_percentiles.iterator();
        while (iterator.hasNext()) {
            Percentile next = iterator.next();
            double percent = next.getPercent();
            double value = next.getValue();
            System.err.println(percent+" : "+value);
        }

        client.close();

    }
}
